package com.kaka.bus.engine.home.main;

import android.Manifest;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.kaka.bus.R;
import com.kaka.bus.adapter.MainAdvertisingAdapter;
import com.kaka.bus.adapter.MainProAdapter;
import com.kaka.bus.base.fragment.BaseFragment;
import com.kaka.bus.bean.AppInfo;
import com.kaka.bus.bean.DrainProductBean;
import com.kaka.bus.bean.HttpWrapper;
import com.kaka.bus.bean.Lianxi;
import com.kaka.bus.bean.LoanBean;
import com.kaka.bus.bean.Rolling;
import com.kaka.bus.bean.Status;
import com.kaka.bus.constant.Constant;
import com.kaka.bus.di.component.DaggerLoanComponent;
import com.kaka.bus.engine.amount.TopProduct.TopProductActivity;
import com.kaka.bus.engine.amount.loanproduct.LoanProductActivity;
import com.kaka.bus.engine.borrow.pact.PactGreementActivity;
import com.kaka.bus.engine.prompt.PromptActivity;
import com.kaka.bus.engine.result.ResultActivity;
import com.kaka.bus.engine.user.login.LoginActivity;
import com.kaka.bus.listener.Listener;
import com.kaka.bus.util.GlideImageLoader;
import com.kaka.bus.util.ToastUtil;
import com.kaka.bus.util.U;
import com.kaka.bus.util.UserUtil;
import com.kaka.bus.util.logger.Logger;
import com.kaka.bus.view.BannerIndicator;
import com.kaka.bus.view.RecyclerItemDecoration;
import com.kaka.bus.view.VerticalScrollView;
import com.kaka.bus.view.dialog.TempletDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import butterknife.BindView;

/**
 * BindView
 * Created by OnionMac on 2018/7/11.
 * <p>广告
 * mainFragment2
 */

public class MainFragment2 extends BaseFragment<MainPresenter> implements MainContract.View {


    @BindView(R.id.main_vp_banner)
    Banner mMainVpBanner;
    @BindView(R.id.main_banner_indicator)
    BannerIndicator mMainBannerIndicator;
    @BindView(R.id.main_money)
    TextView mMainMoney;
    @BindView(R.id.main_vertical)
    VerticalScrollView mMainVertical;
    @BindView(R.id.main_recy)
    RecyclerView mMainRecy;
    @BindView(R.id.recycler)
    RecyclerView recycler;
//    @BindView(R.id.mainlist_muti)
//    MutipleLayout mainlist_muti;
    @BindView(R.id.mainlist_smart)
    SmartRefreshLayout mainlist_smart;
    @BindView(R.id.img_notice)
    ImageView img_notice;
    @BindView(R.id.btn_go)
    Button btn_go;
    @BindView(R.id.tv_today)
    TextView tv_today;
    private int mPage = 1;
    private int mPageSize = 10;
    private static final int GOLIMIT = 1;
    private static final int GOPACT = 2;
    private static final int REFURES = 3;
    private static final int BLACK = 4;
    private static final int CHECK = 5;
    private int mStatusCode = 0;
    private String mProductId;
    private String mBannerId;
    private List<LoanBean> mLoanList;
    private List<String> rollings;
    private List<DrainProductBean> mDatas = new ArrayList<>();
    /**
     * 是否认证完成
     */
    private boolean mIsAuth;
    private List<Rolling.BannerBean> mBannerList;
    private MainProAdapter mMainProAdapter;
    private MainAdvertisingAdapter advertisingAdapter;
    private RxPermissions mRxPermissions;
    private TempletDialog mDialog;
    private AppCompatButton btn_sure;
    private AppInfo appInfo;
    private List<Rolling.AdBannerBean> adBanners = new ArrayList<>();
    private String money;

    public static MainFragment2 getInstance(String value) {
        MainFragment2 mainFragment = new MainFragment2();
        Bundle bundle = new Bundle();
        bundle.putString("value", value);
        mainFragment.setArguments(bundle);
        return mainFragment;
    }

    @Override
    protected void doOnceOnFragmentLifecycle() {
        super.doOnceOnFragmentLifecycle();
        mMainVpBanner.setImageLoader(new GlideImageLoader());
        mMainVpBanner.setBannerStyle(BannerConfig.NOT_INDICATOR);
        mMainVpBanner.setBannerAnimation(Transformer.Accordion);
        mMainVpBanner.setDelayTime(5000);
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
//        mainlist_muti.setEmptyText("暂无数据!");
//        mainlist_muti.setEmptyImage(R.drawable.empty_view_kongtai);
//        mainlist_muti.setStatus(MutipleLayout.Loading);
        Typeface typeface = Typeface.createFromAsset(mActivity.getAssets(), "HELVETICANEUELTPRO-MDCN_0.OTF");
        mMainMoney.setTypeface(typeface);

        mLoanList = new ArrayList<>();
        mMainProAdapter = new MainProAdapter(getActivity(), R.layout.item_main_hot, mDatas);
        mMainRecy.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false));
        mMainRecy.setAdapter(mMainProAdapter);
        advertisingAdapter = new MainAdvertisingAdapter(mActivity, R.layout.item_mainadvertsing, adBanners);
        recycler.setLayoutManager(new GridLayoutManager(mActivity, 2));
        recycler.setAdapter(advertisingAdapter);
        recycler.addItemDecoration(new RecyclerItemDecoration(26, 2));
        mRxPermissions = new RxPermissions(mActivity);
        if (mDialog == null) {
            mDialog = new TempletDialog.Builder(getActivity())
                    .setLayout(R.layout.dialog_undone).setWidthPer(0.8).setMoveY(-20)
                    .setWindowAnim(R.style.person＿dialog_anim).build();
            mDialog.setCancelable(false);
            mDialog.setCanceledOnTouchOutside(true);
        }
    }

    @Override
    protected void initData() {
        super.initData();
        refreshUserStatus();
        rollings = new ArrayList<>();
        getData();
    }

    public void getData() {
        mPage = 1;
        mDatas.clear();
        mPresenter.getHotPro(getUserId(), 1, mPageSize);
        mPresenter.getRolling(getUserId(), getToken(), Constant.PLATFORM, U.getAppInfo(getActivity()).getVersionName());
    }


    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        appInfo = U.getAppInfo(getActivity());
        refreshUserStatus();
    }

    public void refreshUserStatus() {
        if (getUserId() != null) {
            mPresenter.checkBpm(getUserId(), getToken());
        }
    }


    @Override
    protected void initListener() {
        mMainVpBanner.setOnPageChangeListener(new ViewPager.OnPageChangeListener()

        {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (mMainBannerIndicator != null) {
                    mMainBannerIndicator.refresh(position);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        btn_go.setOnClickListener(v -> {
            if (TextUtils.isEmpty(getUserId())) {
                startActivity(new Intent(getActivity(), LoginActivity.class));
            } else {

                if (!TextUtils.isEmpty(mBannerId) && !TextUtils.isEmpty(mProductId)) {
                    mPresenter.chargeApply("view", mProductId, mBannerId, Constant.PLATFORM, getUserId(), "1");
                }
                if (checkStatus()) {
                    Intent intent = new Intent(getActivity(), LoanProductActivity.class);
                    intent.putExtra(LoanProductActivity.PROID, mProductId);
                    intent.putExtra(LoanProductActivity.BANNERID, mBannerId);
                    intent.putExtra(LoanProductActivity.MONEY, money); //TODO 1.3.0必看
                    startActivity(intent);
                }
            }
        });

        mMainVpBanner.setOnBannerListener(position ->
        {
            String productId = mBannerList.get(position).getProductId();
            if (TextUtils.isEmpty(productId) || "0".equals(productId)) {
                if (TextUtils.isEmpty(mBannerList.get(position).getDirectUrl())) {
                    return;
                }
                Intent intent = new Intent(mActivity, PactGreementActivity.class);
                intent.putExtra(PactGreementActivity.TYPE, PactGreementActivity.TYPE_LOAD_URL);
                intent.putExtra(PactGreementActivity.TITLE, Constant.APPNAME);
                intent.putExtra(PactGreementActivity.URL, mBannerList.get(position).getDirectUrl());
                startActivity(intent);
            } else {
                if (TextUtils.isEmpty(getUserId())) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                } else {
                    mPresenter.chargeApply("view ", mBannerList.get(position).getProduct().getId(), mBannerList.get(position).getLocationId(), Constant.PLATFORM, getUserId(), "1");
                    if (mBannerList.get(position).getProduct().getIsSelf().toLowerCase().equals("y")) {
                        if (checkStatus()) {

                            Intent intent = new Intent(mActivity, LoanProductActivity.class);
                            intent.putExtra(LoanProductActivity.PROID, mBannerList.get(position).getProductId());
                            intent.putExtra(LoanProductActivity.BANNERID, mBannerList.get(position).getLocationId());
                            intent.putExtra(LoanProductActivity.MONEY, money);
                            startActivity(intent);
                        }
                    } else {
                        Intent intent = new Intent(mActivity, TopProductActivity.class);
                        intent.putExtra(TopProductActivity.PRODUCTBEAN, mBannerList.get(position).getProduct());
                        intent.putExtra(TopProductActivity.PRODUCTID, mBannerList.get(position).getProductId());
                        intent.putExtra(TopProductActivity.BANNERID, mBannerList.get(position).getLocationId());
                        startActivity(intent);
                    }

                }
            }
        });
        advertisingAdapter.setOnItemClickListener((adapter, view, position) -> {
            String productId = adBanners.get(position).getProductId();
            if (TextUtils.isEmpty(productId) || "0".equals(productId)) {
                if (TextUtils.isEmpty(adBanners.get(position).getDirectUrl())) {
                    return;
                }
                Intent intent = new Intent(mActivity, PactGreementActivity.class);
                intent.putExtra(PactGreementActivity.TYPE, PactGreementActivity.TYPE_LOAD_URL);
                intent.putExtra(PactGreementActivity.TITLE, Constant.APPNAME);
                intent.putExtra(PactGreementActivity.URL, adBanners.get(position).getDirectUrl());
                startActivity(intent);
            } else {
                if (TextUtils.isEmpty(getUserId())) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                } else {
                    mPresenter.chargeApply("view ", adBanners.get(position).getProduct().getId(), adBanners.get(position).getLocationId(), Constant.PLATFORM, getUserId(), "1");
                    if (adBanners.get(position).getProduct().getIsSelf().toLowerCase().equals("y")) {

                        if (checkStatus()) {
                            Intent intent = new Intent(mActivity, LoanProductActivity.class);
                            intent.putExtra(LoanProductActivity.PROID, adBanners.get(position).getProductId());
                            intent.putExtra(LoanProductActivity.BANNERID, adBanners.get(position).getLocationId());
                            intent.putExtra(LoanProductActivity.MONEY, money);
                            startActivity(intent);
                        }


                    } else {
                        Intent intent = new Intent(mActivity, TopProductActivity.class);
                        intent.putExtra(TopProductActivity.PRODUCTBEAN, adBanners.get(position).getProduct());
                        intent.putExtra(TopProductActivity.PRODUCTID, adBanners.get(position).getProductId());
                        intent.putExtra(TopProductActivity.BANNERID, adBanners.get(position).getLocationId());
                        startActivity(intent);
                    }

                }
            }

        });

        mainlist_smart.setOnRefreshListener(refreshlayout -> {
            getData();
        });

        mainlist_smart.setOnLoadmoreListener(refreshlayout -> {
            mPresenter.loadMore(getUserId(),++mPage, mPageSize);
        });
//        mainlist_muti.setOnReloadListener(v -> {
//            getData();
//        });
        mMainProAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.btn_apply) {
                if (TextUtils.isEmpty(getUserId())) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                } else {

                    DrainProductBean.ProductBean bean = mDatas.get(position).getProduct();
                    mPresenter.chargeApply("view ", mDatas.get(position).getProductId(), mDatas.get(position).getLocationId(), Constant.PLATFORM, getUserId(), "1");
                    if (bean.getIsSelf().toLowerCase().equals("y")) {

                        if (checkStatus()) {
                            Intent intent = new Intent(getActivity(), LoanProductActivity.class);
                            intent.putExtra(LoanProductActivity.PROID, mDatas.get(position).getProductId());
                            intent.putExtra(LoanProductActivity.BANNERID, mDatas.get(position).getLocationId());
                            intent.putExtra(LoanProductActivity.MONEY, money);
                            startActivity(intent);
                        }

                    } else {
                        Intent intent = new Intent(getActivity(), TopProductActivity.class);
                        intent.putExtra(TopProductActivity.PRODUCTBEAN, mDatas.get(position).getProduct());
                        intent.putExtra(TopProductActivity.PRODUCTID, mDatas.get(position).getProductId());
                        intent.putExtra(TopProductActivity.BANNERID, mDatas.get(position).getLocationId());
                        startActivity(intent);
                    }
                }
            }
        });
    }

    /**
     * 审核中
     */
    private void check() {
        Intent intent = new Intent(mActivity, ResultActivity.class);
        intent.putExtra(ResultActivity.RESULT_TYPE, ResultActivity.PERSON_CHECK);
        startActivity(intent);
    }

    private boolean checkStatus() {
        if (mStatusCode == REFURES) {
            Intent intent = new Intent(mActivity, PromptActivity.class);
            intent.putExtra(PromptActivity.STATUTYPE, PromptActivity.REFURES);
            startActivity(intent);
//            U.showDialogJuJue(mActivity, Constant.REFUES);
            return false;
        } else if (mStatusCode == BLACK) {
//            U.showDialogJuJue(mActivity, Constant.BLACK);
            Intent intent = new Intent(mActivity, PromptActivity.class);
            intent.putExtra(PromptActivity.STATUTYPE, PromptActivity.BLACK);
            startActivity(intent);
            return false;
        } else if (mStatusCode == CHECK) {
            check();
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void getRollingSuccess(HttpWrapper<Rolling> rolling) {
//        mainlist_muti.setStatus(MutipleLayout.Success);
        if (Constant.SUCCESS_CODE.equals(rolling.code)) {
            mProductId = rolling.getData().getSelfProductId();
            mBannerId = rolling.getData().getSelfLocationId();
            money = rolling.getData().getMaxLoanMoney();
            mMainMoney.setText(rolling.getData().getMaxLoanMoney());

            if (rolling.getData().getRolling() != null && rolling.getData().getRolling().size() > 0) {
                mMainVertical.setVisibility(View.VISIBLE);
                img_notice.setVisibility(View.VISIBLE);
                rollings.clear();
                rollings.addAll(rolling.getData().getRolling());
                mMainVertical.setData(rollings);
                mMainVertical.start();
            } else {
                mMainVertical.setVisibility(View.GONE);
                img_notice.setVisibility(View.GONE);
            }
            if (rolling.getData().getBanner() != null && rolling.getData().getBanner().size() > 0) {
                UserUtil.setCache(UserUtil.SERVICE, rolling.getData());
                List<String> list = new ArrayList<>();
                list.clear();
                mBannerList = rolling.getData().getBanner();
                if (mBannerList == null) {
                    return;
                }
                for (Rolling.BannerBean bannerBean : mBannerList) {
                    list.add(bannerBean.getUrl());
                }
                mMainVpBanner.setImages(list);
                mMainBannerIndicator.setSize(list.size());
                mMainVpBanner.start();
            }
            if (rolling.getData().getAdBanner() != null && rolling.getData().getAdBanner().size() > 0) {
                adBanners.clear();
                adBanners.addAll(rolling.getData().getAdBanner());
                advertisingAdapter.notifyDataSetChanged();
            }

        } else {
            showMessage(rolling.getInfo());
        }
    }

    @Override
    public void checkBpmSuccess(HttpWrapper<Status> s) {
        mStatusCode = 0;
        if (Constant.TOKEN_TIMEOUT.equals(s.code)) {
            U.tokenOut(mActivity);
        } else if (Constant.NODE_NO.equals(s.code)) {
            String data = s.getData().getCodes();
            if ("4".equals(data)) {
                // 拉通讯录
                mRxPermissions.request(Manifest.permission.READ_CONTACTS, Manifest.permission.READ_PHONE_STATE)
                        .subscribe(aBoolean -> {
                            if (aBoolean) {
                                uploadContact();
                            } else {
                                U.getSingleDialog(mActivity, "温馨提示", "您已经拒绝了权限,请在设置-应用管理中打开读取通讯录权限", "了解", null).show();
                            }
                        });
            } else if ("r".equals(data)) {
                mStatusCode = BLACK;
            } else {
                mStatusCode = GOLIMIT;
            }
        } else if (Constant.NODE_OK.equals(s.code)) {
            mStatusCode = GOLIMIT;
            mIsAuth = true;
        } else if (Constant.SUCCESS_CODE.equals(s.code)) {
            mIsAuth = true;
            mStatusCode = GOLIMIT;
        } else if ("300".equals(s.code)) {
            mStatusCode = REFURES;
        } else if ("308".equals(s.code)) {
            mStatusCode = CHECK;
        }
    }

    /**
     * 上传通讯录
     */
    private void uploadContact() {
        new Thread() {
            @Override
            public void run() {
                HashSet<Lianxi> allContactInfo = U.queryContacts(mActivity);
                if (allContactInfo.size() == 0) {
                    mActivity.runOnUiThread(() -> U.getSlectDialog(mActivity, "提示", "通讯录为空读取通讯录权限可能被拒绝,请先开启权限", "取消", "前去设置",
                            new Listener.OnNormalAlertDialogChooseClickListener() {
                                @Override
                                public void onLeft() {

                                }

                                @Override
                                public void onRight() {
                                    Intent intent = new Intent();
                                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                    Uri uri = Uri.fromParts("package", mActivity.getPackageName(), null);
                                    intent.setData(uri);
                                    mActivity.startActivity(intent);
                                }
                            }).show());
                    return;
                }

                String json = new Gson().toJson(allContactInfo);
                Logger.i("联系人提交的信息" + allContactInfo.size() + "---" + json);
                mPresenter.uploadContact(getUserId(), json);
            }
        }.start();
    }

    @Override
    public void uploadContactSuccess(HttpWrapper<String> s) {
        if (Constant.SUCCESS_CODE.equals(s.code)) {
            mPresenter.checkBpm(getUserId(), getToken());
        } else {
            showMessage(s.getInfo());
            uploadContactFaild();
        }
    }

    @Override
    public void hotProSyccess(HttpWrapper<List<DrainProductBean>> s) {
        getData();
    }

    @Override
    public void onResultStart(HttpWrapper<List<DrainProductBean>> o) {
        mainlist_smart.finishRefresh(0);
        if (Constant.SUCCESS_CODE.equals(o.code)) {
            if (o.data != null && o.data.size() > 0) {
                tv_today.setVisibility(View.VISIBLE);
                mMainProAdapter.addData(o.getData());
                mMainProAdapter.notifyDataSetChanged();
            } else {
                tv_today.setVisibility(View.GONE);
            }
        } else if (Constant.ERROR_CODE.equals(o.getCode())) {
            showMessage(o.getInfo());
            onError();
        } else if (Constant.TOKEN_TIMEOUT.equals(o.code)) {
            U.tokenOut(mActivity);
        } else if ("202".equals(o.code)) {
            tv_today.setVisibility(View.GONE);
            mDatas.clear();
            mMainProAdapter.notifyDataSetChanged();
        } else {
            showMessage(o.getInfo());
        }
    }

    @Override
    public void onResultLoadMore(HttpWrapper<List<DrainProductBean>> o) {

        mainlist_smart.finishLoadmore(0);
        if (Constant.SUCCESS_CODE.equals(o.getCode())) {
            if (o.data != null && o.data.size() > 0) {
                mMainProAdapter.addData(o.data);
                mMainProAdapter.notifyDataSetChanged();
            } else {
                showMessage("没有更多数据了");
                mPage--;
            }
        } else if (Constant.ERROR_CODE.equals(o.getCode())) {
            showMessage(o.getInfo());
            onError();
        } else if("203".equals(o.getCode())){
            showMessage(o.getInfo());
            onError();
        } else if (Constant.TOKEN_TIMEOUT.equals(o.code)) {
            U.tokenOut(mActivity);
        }

    }

    @Override
    public void refresh(HttpWrapper<List<DrainProductBean>> data) {
        if (Constant.SUCCESS_CODE.equals(data.code)) {
            getData();
            refreshUserStatus();
        } else {
            ToastUtil.showShort(mActivity, "取消失败！");
        }
    }

    @Override
    public void onStartError() {
        mainlist_smart.finishRefresh(0);
    }

    @Override
    public void uploadContactFaild() {
        U.getSingleDialog(mActivity, "温馨提示", "信息获取有误,请重新尝试", "确定", null).show();
    }

    @Override
    public void nodeOk(HttpWrapper<String> data) {
        if (Constant.SUCCESS_CODE.equals(data.getCode())) {

        } else if (Constant.TOKEN_TIMEOUT.equals(data.code)) {
            U.tokenOut(mActivity);
        }
    }

    @Override
    public void onDestroy() {
        if (null != mDialog) {
            mDialog = null;
        }
        super.onDestroy();
    }


    @Override
    public void onError() {
        mPage--;

        if(mainlist_smart.isLoading()){
            mainlist_smart.finishLoadmore(0);
        }

        if(mainlist_smart.isRefreshing()){
            mainlist_smart.finishRefresh();
        }

//        mainlist_muti.setStatus(MutipleLayout.Error);
    }


    @Override
    public void commitContactSuccess(HttpWrapper<String> bean) {

    }

    @Override
    public void getBorrowFaild() {

    }


    @Override
    protected void initInject() {
        DaggerLoanComponent.builder().activityComponent(getFragmentComponent()).build().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_main3;
    }

}
